package com.wn.servlet.resp;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

/**
 * @author yellow Docter
 * @date 2022 -06-29
 * @desc
 *
 * resp  这个对给 页面进回写操作
 *  getWriter();  获取流 通过这个流给浏览器回写数据
 *  resp.setContentType("text/html;charset=utf-8"); 解决中文乱码问题
 *  resp.getWriter().write("hello resp");
 *
 *  获取输出流,可以回写二进制
 *   resp.getOutputStream();
 *
 */
@WebServlet("/resp01")
public class Resp01Servlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 01  回写字符串
//        resp.getWriter().write("hello resp");
        // 中文 出现乱码
        // 解决: 告诉浏览器用什么编码
        // 告诉 浏览器的 数据格式和编码格式
//        resp.setContentType("text/html;charset=utf-8");
//        resp.getWriter().write("中了500W美元");

        //02 回写 字符打印输出流
//        resp.setContentType("text/html;charset=utf-8");
//        PrintWriter out = resp.getWriter();
//        out.write("<head>");
//        out.write("<title>登录页面</title>");
//        out.write("</head>");
//        out.write("<body>");
//        out.write("<h1>登录成功</h1>");
//        out.write("</body>");
//        out.write("</html>");

        //03 回写 byte 数组

//        byte[] bytes = "hello".getBytes();
//        ServletOutputStream outputStream = resp.getOutputStream();
//        outputStream.write(bytes);
//        outputStream.close();

        // 读取 写
        InputStream is = getServletContext().getResourceAsStream("/img/a.webp");
        ServletOutputStream os = resp.getOutputStream();

        byte [] b = new byte[1024];
        int len = 0;
        while ((len = is.read(b)) != -1){
            os.write(b,0,len);
            os.flush();
        }
        is.close();
        os.close();

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
